package service

import (
	"tylnmall/models"
	"github.com/jinzhu/gorm"
	"common/logger"
	"errors"
)

type List struct {
	Id      int
	Type    int
	Name    string
	Img     string
	ComList []*models.Commodity
	StoList []*models.Story
}

func ModuleAndMoList(lists []*List, db *gorm.DB) ([]*List, error) {
	var err error
	var module []*models.HomeModuleCommodity
	for _, list := range lists {
		if err = db.Where("home_module_id = ?", list.Id).Find(&module).Error; err != nil {
			logger.Error(err)
			err = errors.New("module not found")
			logger.Error(err)
			return lists, err
		}
		if list.Type == 0 {
			var re []*models.Commodity
			var l []int
			for _, m := range module {
				l = append(l, m.ModuleId)
			}
			if err = db.Where("id in (?)", l).Find(&re).Error; err != nil {
				logger.Error(err)
				err = errors.New("module not found")
				logger.Error(err)
				return lists, err
			}
			list.ComList = re
		} else {
			var re []*models.Story
			var l []int
			for _, m := range module {
				l = append(l, m.ModuleId)
			}
			if err = db.Where("id in (?)", l).Find(&re).Error; err != nil {
				logger.Error(err)
				err = errors.New("module not found")
				logger.Error(err)
				return lists, err
			}
			list.StoList = re
		}

	}
	return lists, nil
}
